package flash;

import gnu.io.SerialPort;

import java.util.Calendar;
import java.util.List;

import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.akeil.flash.dataprocessing.FlashC51CommandTransfer;
import com.akeil.flash.dataprocessing.FlashC51Processor;
import com.akeil.flash.dialog.LicenseDialog;
import com.akeil.flash.model.FlashData;
import com.akeil.flash.utils.SerialTimerManager;
import com.akeil.flash.utils.StatusTimerManager;
import com.akeil.flash.view.CalibrationView;
import com.akeil.flash.view.ResultView;
import com.yang.serialport.manage.SerialPortManager;
import com.yang.serialport.utils.AppMD5Util;
import com.yang.serialport.utils.ByteUtils;
import com.yang.serialport.utils.SoftwareGrantControl;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {
	public static ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config/applicationContext.xml");
	public static SerialPort serialport = null;
	public static FlashData flashData = new FlashData();
	public static FlashC51Processor processor = new FlashC51Processor(true,new FlashC51CommandTransfer());
	public static ResultView resultView = (ResultView)Application.applicationContext.getBean("resultView");
	//public static CalibrationView calibrationView = (CalibrationView)Application.applicationContext.getBean("calibrationView");
	public static StatusTimerManager statusTimerManager = null;
	public static SerialTimerManager serialTimerManager = SerialTimerManager.getInstance(flashData);
	
	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
	 */
	public Object start(IApplicationContext context) {
		Display display = PlatformUI.createDisplay();
		
		List<String> portnames = SerialPortManager.findPort();
		if(portnames != null && portnames.size() > 0){
			System.out.println(portnames);
		}else{
			final Shell shell = Display.getCurrent().getActiveShell();  
			MessageDialog.openError(shell, "错误提示", "没有找有串口！");
		}
		
		String store_pwd = Activator.getDefault().getPreferenceStore().getString("md5_password");//获取保持的MD5密码
		String real_pwd = "";
		try {
			//real_pwd = AppMD5Util.getMD5(ByteUtils.intToHexString(Integer.parseInt(SoftwareGrantControl.getHardDiskSN("c")) , true) + AppMD5Util.author + AppMD5Util.product + LocalMAC.getLocalMACstr());
			real_pwd = AppMD5Util.getMD5(ByteUtils.intToHexString(Integer.parseInt(SoftwareGrantControl.getHardDiskSN("c")) , true) + AppMD5Util.author + AppMD5Util.product);
			//real_pwd = AppMD5Util.getMD5(IpUtil.getLocalMac("127.0.0.1") + AppMD5Util.author + AppMD5Util.product);
			//real_pwd = AppMD5Util.getMD5(IpUtil.getCPUID_Windows() + AppMD5Util.author + AppMD5Util.product);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}//根据C盘序列号，生成MD5密码
		
		if(real_pwd.compareTo(store_pwd) != 0){//不一致
			final Shell shell = Display.getCurrent().getActiveShell();  
		    try {// 
		        final LicenseDialog loginDialog = new LicenseDialog(shell);  
		        final int result = loginDialog.open();  
		        // final int result = 0;  
		        if (result == IDialogConstants.OK_ID) {  
		        	Activator.getDefault().getPreferenceStore().setValue("md5_password",real_pwd);		           
		        }  else {
		        	long start_day_ms = Activator.getDefault().getPreferenceStore().getLong("start_time_millis");
		        	long now_day_ms = System.currentTimeMillis();
		        	
		        	if(start_day_ms > 0L){
		        	    if((now_day_ms - start_day_ms)/1000 > (30 * 24 * 3600)){// 2592000000
		        	    	return IApplication.EXIT_OK;
		        	    }		        	    
		        	}else{
		        		Calendar c2 = Calendar.getInstance();
		        		Activator.getDefault().getPreferenceStore().setValue("start_time_millis",System.currentTimeMillis());
		        	}
		        	//return IApplication.EXIT_OK;
		        }
		    } catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			} finally {  
		        if (shell != null) {  
		            shell.dispose();  
		        }  
		    }  
		}
		////////////////////////////////////////////////////////
		display = PlatformUI.createDisplay();
		try {
			int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
			if (returnCode == PlatformUI.RETURN_RESTART) {
				return IApplication.EXIT_RESTART;
			}
			return IApplication.EXIT_OK;
		} finally {
			display.dispose();
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	public void stop() {
		if (!PlatformUI.isWorkbenchRunning())
			return;
		final IWorkbench workbench = PlatformUI.getWorkbench();
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}
}
